/*
 * @Author: 谢小康 2170673706@qq.com
 * @Date: 2023-12-08 14:27:33
 * @LastEditors: 谢小康 2170673706@qq.com
 * @LastEditTime: 2024-01-19 19:18:55
 * @FilePath: \My-bolg\server\util\user.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

/* 登录的参数校验 */
const Response = require('./respanse.js')
const {
    escape
} = require('./utils.js');
const jwt = require("./jwt.js")
/* 登录的参数检验和参数的转义 */
const ParameterValidation = (req, res, next) => {
    try {
        let dataArraylist = Object.entries(req.body);
        /* 对于参数的数量的校验 */
        if (dataArraylist.length != 2) {
            let config = {
                code: 400,
                message: '参数错误',
                err: null
            }
            return Response.errorresponse(res, config)
        }
        if ((req.body?.username ?? false) && (req.body?.password ?? false)) {
            /* 对于参数的类型校验 */
            if (typeof req.body?.username != 'string' || typeof req.body?.password != 'string') {
                let config = {
                    code: 400,
                    message: '参数类型错误',
                    err: null
                }
                return Response.errorresponse(res, config)
            }
        } else {
            let config = {
                code: 400,
                message: '参数名称错误',
                err: null
            }
            return Response.errorresponse(res, config)
        }
        /* 对于特殊字符的转义 */
        for (let [key, value] of dataArraylist) {
            req.body[key] = escape(value);
        }
        console.log(req.body?.username, req.body?.password);
        next()

    } catch (error) {
        next(new Error(error, 'util-User.js 登录参数校验出错'))
    }
}
/* 校验是否登录 校验token */
const auth = async (req,res,next)=>{
    try {
        if(req.headers?.authorization){
            let token = req.headers.authorization.split(" ")[1];
            jwt.verify(token);
            next()
        }else{
            console.error("您没有权限访问，请先登录");
            Response.errorresponse(res,{
                code:401,
                message:"您没有权限访问，请先登录",
            })
        }
    } catch (err) {
        switch (err.name) {
            case "TokenExpiredError":
              console.error("token已过期-在util-user.js");
              Response.errorresponse(res,{
                code:401,
                message:"token过期",
            })
              break;
            case "JsonWebTokenError":
              console.error("无效的token-在util-user.js");
                Response.errorresponse(res,{
                    code:401,
                    message:"无效的token",
            })
            break;
        }
    }
}

module.exports = {
    ParameterValidation,
    auth,
};